package com.jack.leetcode.string;

/*** 
 * @author zhangjie
 * @date 2020/4/23 21:55
 */
public class 最长回文子串 {

    public static void main(String[] args) {
        String s = "abbc";
        System.out.println(longestPalindrome(s));
    }

    public static String longestPalindrome(String s) {
        if (s == null || "".equals(s)) {
            return "";
        }
        int n = s.length();
        String rev = new StringBuffer(s).reverse().toString();
        int[][] arr = new int[n][n];
        int maxLen = 0;
        int maxEnd = 0;
        for (int i = 0; i < n ; i++) {
            for (int j = 0; j < n; j++) {
                if (s.charAt(i) == rev.charAt(j)) {
                    if (i == 0 || j == 0) {
                        arr[i][j] = 1;
                    } else {
                        arr[i][j] = arr[i - 1][j - 1] + 1;
                    }
                }
                if (arr[i][j] > maxLen) {
                    int beforeRev = n - 1 - j;
                    if (beforeRev + arr[i][j] - 1 == i) {
                        maxLen = arr[i][j];
                        maxEnd = i;
                    }
                }
            }
        }
        return s.substring(maxEnd-maxLen+1,maxEnd+1);
    }
}
